package com.example.demo.config.shiro.filter;

import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.demo.ResBean.constant.RedisConstant;
import com.example.demo.entity.sqlbean.JWTToken;
import com.example.demo.utils.ApplicationContextUtils;
import com.example.demo.utils.RedisUtils;
import com.example.demo.utils.TokenUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author 幻
 * @date 2021-05-18 16:30
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("========preHandle方法执行=========");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-control-Allow-Origin", req.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        res.setHeader("Access-control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            res.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 是否允许访问,如果带有Authorization,则对Authorization进行检查,否则直接通过
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        System.out.println("======isAccessAllowed方法执行===========");
        //判断请求头时候包含Authorization
        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                /*
                 *注意这里捕获的异常其实是在Realm抛出的，但是由于executeLogin（）方法抛出的异常是从login（）来的，
                 * login抛出的异常类型是AuthenticationException，所以要去获取它的子类异常才能获取到我们在Realm抛出的异常类型。
                 * */
                String msg = e.getMessage();
                Throwable cause = e.getCause();
                System.out.println("msg=" + msg);
                if (cause instanceof SignatureVerificationException) {
                    // 该异常为JWT的AccessToken认证失败(Token或者密钥不正确)
                    msg = "token或者密钥不正确(" + cause.getMessage() + ")";
                } else if (cause instanceof TokenExpiredException) {
                    //AccessToken过期，尝试去刷新token
                    if (refreshToken(request, response)) {
                        return true;
                    }
                }
                responseError(response, msg);
            }
        }
        //需要游客登录则需要返回true
        return false;
    }

    /**
     * 这里我们详细说明下为什么重写 可以对比父类方法，只是将executeLogin方法调用去除了
     * 如果没有去除将会循环调用doGetAuthenticationInfo方法
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        this.sendChallenge(request, response);
        return false;
    }

    /**
     * 判断header中是否有token
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        System.out.println("=====isLoginAttempt方法执行======");
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        if (token == null || "".equals(token)) {
            responseError(response, "没有找到token,没有权限访问!");
            return false;
        }
        return true;
    }

    /**
     * 进行AccessToken登录认证授权
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("=======executeLogin方法执行============");
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");
        JWTToken jwt = new JWTToken(token);
        //交给自定义的realm对象去登录，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwt);
        //没有抛出异常则表示登录成功
        return true;
    }

    /**
     * 将非法请求跳转到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) {
        System.out.println("responseError");

        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            message = URLEncoder.encode(message, "UTF-8");
            httpServletResponse.sendRedirect("/Manageterminal/user/unauthorized?message=" + message);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 刷新token,，进行判断RefreshToken是否过期，未过期就返回新的AccessToken且继续正常访问
     */
    private boolean refreshToken(ServletRequest request, ServletResponse response) {
        System.out.println("refreshToken-执行");

        HttpServletRequest req = (HttpServletRequest) request;
        ApplicationContextUtils.getBean("redisUtils");
        //获取传递过来的accessToken
        String accessToken = this.getAuthzHeader(request);
        //获取Token中的username
        String username = TokenUtils.getUsername(accessToken);
        //判断refreshToken是否过期了，过期了那么所含的token的键不存在
        String hashKey = RedisConstant.TOKEN_NAME + username;
        if (RedisUtils.hasKey(hashKey) &&
                RedisUtils.hHasKey(hashKey, accessToken)) {
            //判断refresh的时间节点和传递过来的accessToken的时间节点是否一致，不一致校验失败
            long current = (long) RedisUtils.hget(hashKey, accessToken);
            if (current == TokenUtils.getExpire(accessToken)) {
                //获取当前时间节点
                long currentTimeMillis = System.currentTimeMillis();
                //生成刷新的token
                String token = TokenUtils.createToken(username, currentTimeMillis);
                //删除以前的token
                RedisUtils.hdel(hashKey, accessToken);
                //刷新redis里面的refreshToken,过期时间是7天
                RedisUtils.hset(hashKey, token, currentTimeMillis, TokenUtils.REDIS_EXPIRE_TIME);
                try {
                    //再次交给shiro进行认证
                    JWTToken jwt = new JWTToken(token);
                    getSubject(request, response).login(jwt);
                    // 最后将刷新的AccessToken存放在Response的Header中的Authorization字段返回
                    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                    httpServletResponse.setHeader("Authorization", token);
                    httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        }
        return false;
    }
}
